package action

import (
	"strings"

	"gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"

	"ssdevice/common/utils"
	"ssdevice/internal/device/models"
)

type Funcs struct {
	Orm *gorm.DB
}

func (action *Funcs) Execute(topic string, jsonData map[string]interface{}) {
	devSn := strings.Split(topic, "/")[3]
	_, to := AutoLogin(action.Orm, devSn, jsonData)
	if strings.HasSuffix(topic, "/func") {
		// 功能控制上报
		targetSn := utils.If(len(to) > 0 && to != devSn, to, devSn).(string)
		funcObj := utils.GetMapValueFiled(jsonData, "data")
		now := utils.GetNowTimeStr()
		if funcObj != nil {
			action.funcUpdate(targetSn, funcObj)
		}
		// 更新dev状态
		UpdateLiveStatus(action.Orm, devSn, to, now)
	}
}

// func模型更新
func (action *Funcs) funcUpdate(devSn string, funObj map[string]interface{}) {
	if len(funObj) == 0 {
		return
	}
	devFunc := &models.SysDevFunc{}
	devFunc.Model.Orm = action.Orm
	if err := devFunc.UpdateDevFunc(devSn, funObj); err != nil {
		logger.Error(err)
		return
	}
}
